package com.will.txj.aj.security.config.auth;

import com.will.txj.aj.global.utils.StringRedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: wen-yi;
 * @date: 2021/12/5 21:57;
 * @Description: 处理单独逻辑验证码 OncePerRequestFilter : 保证过滤器只被调用一次
 */
@Slf4j
// @Component
public class ValidateCodeFilter extends OncePerRequestFilter {
    @Autowired
    private AuthenticationFailureHandler authenctiationFailureHandler;
    @Autowired
    private StringRedisUtil stringRedisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        log.info("RequestURI: {}",uri);// 是一个登陆请求
        if (StringUtils.equals("/oauth/token", request.getRequestURI())
                && StringUtils.equalsIgnoreCase(request.getMethod(), "POST")) {
            try {
                validate(new ServletWebRequest(request));
            } catch (AuthenticationException e) {
                // 有异常就返回自定义失败处理器
                authenctiationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        // 不是一个登录请求，不做校验 直接通过
        filterChain.doFilter(request, response);
    }

    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
        String redisCode = stringRedisUtil.get("aj");
        log.info("redisCode: {}", redisCode);

        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "verifyCode");

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码不能为空！");
        }

        if (StringUtils.isEmpty(redisCode)) {
            throw new ValidateCodeException("验证码已过期");
        }

        if (!StringUtils.equals(redisCode, codeInRequest.trim().toLowerCase())) {
            throw new ValidateCodeException("验证码不匹配");
        }
        stringRedisUtil.delete("aj");
    }
}
